import {
  setStorage,
  getStorage,
  removeStorage,
  setToken,
  setCookies
} from '@/utils'
// import {
//   platformUserInfo
// } from '@/api/user'
import { Login } from '@/api/user'
// import { getToken } from '@/api/databaseBin'
const stateInfo = {
  userId: 'ch',
  nickName: 'ark',
  expiresIn: 4,
  loginType: 0
}

const userInfo = getStorage('userInfo', 0) || stateInfo
const role = getStorage('role', 0) || 'visitor'
const token = getStorage('token', 0)
const visitor = getStorage('visitor', 0)
const account = getStorage('account', 0) || '游客'
const userName = getStorage('userName', 0) || account
const userId = getStorage('userId',0)
const avatar = getStorage('avatar',0)

const state = {
  userInfo,
  token,
  role,
  account,
  visitor,
  userName,
  tokenKey: '',
  userId,
  avatar
}

const getters = {
  role: state => state.role,
  token: state => state.token,
  account: state => state.account,
  visitor: state => state.visitor,
  userInfo: state => state.userInfo,
  userName: state => state.userName,
  userId:state => state.userId,
  avatar:state => state.avatar,
  isVisitor: state =>
    state.token === '' || state.token === undefined || state.token === null // 没有token
}

const mutations = {
  SET_TOKEN_KEY: (state, value) => {
    state.tokenKey = value
  },
  SET_nickName: (state, name) => {
    state.nickName = name
  },
  SET_ROLE: (state, role) => {
    state.role = role
    setStorage('role', role, 0)
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setStorage('token', token, 0)
  },
  SET_DATABASE_TOKEN: (state, token) => {
    state.database_token = token
    setStorage('database_token', token, 0)
  },
  SET_VISITOR: (state, visitor) => {
    state.visitor = visitor
    setStorage('visitor', visitor, 0)
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account
    setStorage('account', account, 0)
  },
  SET_USER_ID: (state,userId) => {
    state.userId = userId
    setStorage('userId', userId, 0)
  },
  SET_AVATAR:(state,avatar) =>{
    state.avatar = avatar
    setStorage('avatar',avatar,0)
  },
  // 设置用户名
  UPDATE_USER_NAME: (state, userName) => {
    state.userName = userName
    setStorage('userName', userName, 0)
  },
  // 设置个人信息
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    setStorage('userInfo', userInfo, 0)
  },
  // 清除个人信息
  REMOVE_USER_INFO(state) {
    state.userInfo = ''
    state.userName = ''
    state.userId = ''
    state.avatar = ''
    removeStorage('userInfo')
    removeStorage('userName')
    removeStorage('userId')
    removeStorage('avatar')
  }
}

const actions = {
  // 保存登录相关信息
  loginIn(context, obj) {
    const hour = obj.expires_in / 3600 // 单位秒转小时
    setToken(`${obj.token_type} ${obj.access_token}`, hour) // token
    setToken(obj.refresh_token, hour, true) // refreshToken
    setStorage('tempToken', obj.access_token, hour) // 每次请求会更新,本地储存
    setCookies('tokenKey', obj.token_type) // 关闭浏览器时会自动清空，不能使用sessionStorage
    context.commit('SET_TOKEN_KEY', obj.token_type)
    setStorage('expiresIn', hour, 0) // 存一个接口返回的token有效时间
  },
  // 获取用户详细信息
  // async getUserInfo(context) {
  //   const { status, data } = await platformUserInfo()
  //   if (status === 1) {
  //     const { userId, account, email } = data
  //     setStorage('userId', userId, 0)
  //     setStorage('nickName', account, 0)
  //     setStorage('email', email, 0)
  //     context.commit('SET_nickName', account)
  //     context.commit('SET_USER_INFO', data)
  //   }
  // },
  // 清空登录信息
  clearAccountInfo(context) {
    // clearStorage()
    context.commit('SET_TOKEN', '')
    context.commit('SET_ROLE', '') // 
    context.commit('SET_ACCOUNT', '') // 游客
    context.commit('UPDATE_USER_NAME', '') // userName清空
    context.commit('SET_USER_ID','')
    removeStorage('token')
    removeStorage('role')
    removeStorage('account')
    removeStorage('userId')
    removeStorage('avatar')
    // context.commit('SET_TOKEN', getStorage('visitor', visitor, 0))
  },
  // 获取知产数仓访问数据的token
  // async getDatabaseBinToken(context) {
  //   const result = await getToken()
  //   context.commit(
  //     'SET_DATABASE_TOKEN',
  //     `${result.token_type} ${result.access_token}`
  //   )
  // },
  LoginForm(context, form) {
    // context.dispatch('clearAccountInfo')
    return new Promise((resolve, reject) => {
      Login(form)
        .then(res => {
          if (res.code === 200) {
            // setStorage('token', res.token, 0)
            if (res.role !== 'youke' && res.role !== 'visitor') {
              context.commit('SET_TOKEN', res.token)
            }
            context.commit('SET_ROLE', res.role)
            let account = ''
            switch (res.role) {
              case 'youke':
              case 'visitor':
                account = '游客'
                context.commit('SET_VISITOR', res.token)
                break
              case 'admin':
                account = '超级管理员'
                context.commit('UPDATE_USER_NAME', account)
                break
              case 'bus':
                account = '平台运营人员'
                context.commit('UPDATE_USER_NAME', account)
                break
              case 'user':
                account = '企业用户'
                break
              case 'common':
                account = '普通角色'
                context.commit('UPDATE_USER_NAME', res.userName)
                break
              default:
                break
            }
            // setStorage('account', account, 0)
            //
            context.commit('SET_ACCOUNT', account)
            context.commit('SET_USER_ID',res.userId)
            context.commit('SET_AVATAR',res.avatar)
          } else {
            // this.$message.success(res.msg)
          }
          resolve(res)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
